﻿using Eneta.Portal.Common.Definitions;
using Microsoft.SharePoint;

namespace Eneta.Portal.Authentication.Live
{
    public static class Extensions
    {
        public static int GetUserProfileID(this SPUser user)
        {
            var siteId = SPContext.Current.Site.ID;
            var id = 0;
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.OpenWeb())
                    {
                        var queryString = "<Where><Eq><FieldRef Name=\"SysID\" /><Value Type=\"Text\">{0}</Value></Eq></Where>";
                        queryString = string.Format(queryString, user.ToString().Substring(7));

                        var query = new SPQuery();
                        query.Query = queryString;

                        var items = web.GetList(Lists.ProfileList).GetItems(query);
                        if (items.Count == 0)
                            return;
                        id = items[0].ID;
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return id;
        }
    }

}
